package com.bckj.fastboot.core.extra.dbsearch.dbmodel;

import com.bckj.fastboot.core.util.ConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.lang.reflect.Field;
import java.util.Set;

@Slf4j
public class DbModelScanner {

    void scan(Set<String> basePackages) throws ClassNotFoundException {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(DbModel.class));
        // 遍历包名，并扫描
        for (String basePackage : basePackages) {
            Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(basePackage);
            for (BeanDefinition beanDefinition : beanDefinitions) {
                log.info("Found annotated class: " + beanDefinition.getBeanClassName());
                Class<?> clazz = Class.forName(beanDefinition.getBeanClassName());
                DbModelFactory.DB_MODEL_MAP.put(clazz, toModelInfo(clazz));
            }
        }
    }

    private DbModelInfo toModelInfo(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        DbModelInfo modelInfo = new DbModelInfo(fields.length);
        for (Field field : fields) {
            if (field.isAnnotationPresent(DbField.class)) {
                DbField dbField = field.getAnnotation(DbField.class);
                modelInfo.fieldToColumn(field.getName(), dbField.column());
            } else {
                modelInfo.fieldToColumn(field.getName(), ConvertUtils.camelCaseToUnderline(field.getName()));
            }
        }
        return modelInfo;
    }
}
